/*
 * @Description: 支持数据传递的增强版 Modal 组件
 * @Author: ZhangHan
 */
import React, { useState, useEffect, useCallback } from "react";
import { Modal, ModalProps } from "antd";

interface ProModalProps<T = any> extends ModalProps {
  /**
   * 传递到 Modal 的数据
   */
  modalData?: T;
  /**
   * 自定义头部渲染函数
   */
  renderHeader?: (data?: T) => React.ReactNode;
  /**
   * 自定义内容渲染函数
   */
  renderContent: (data?: T) => React.ReactNode;
}

function ProModal<T = any>(props: ProModalProps<T>) {
  const { title, modalData, renderHeader, renderContent, width = 520, ...restProps } = props;
  const [headerContent, setHeaderContent] = useState<React.ReactNode>(null);
  const [bodyContent, setBodyContent] = useState<React.ReactNode>(null);

  // 使用useCallback缓存渲染函数
  const renderHeaderContent = useCallback(() => {
    if (renderHeader) return renderHeader(modalData);
    return title ?? "Basic Modal";
  }, [renderHeader, modalData, title]);

  const renderBodyContent = useCallback(() => {
    return renderContent(modalData);
  }, [renderContent, modalData]);

  // 使用useEffect延迟执行，避免在渲染阶段更新状态
  useEffect(() => {
    setHeaderContent(renderHeaderContent());
    setBodyContent(renderBodyContent());
  }, [renderHeaderContent, renderBodyContent]);

  return (
    <Modal {...restProps} title={headerContent} width={width}>
      {bodyContent}
    </Modal>
  );
}

export default ProModal;
